import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { api } from '@/lib/apiService';

export async function GET(req, { params }) {
  try {
    const { id } = await params; // 修复：先await params，然后解构
    if (!id) {
      return NextResponse.json({ error: '缺少ID' }, { status: 400 });
    }
    
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    // 使用带认证的API请求
    const response = await api.auth.get(`prompts/${id}`);
    return NextResponse.json(response);
  } catch (error) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function PUT(req, { params }) {
  try {
    const { id } = await params; // 修复：先await params，然后解构
    if (!id) {
      return NextResponse.json({ error: '缺少ID' }, { status: 400 });
    }

    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const body = await req.json();
    
    // 使用带认证的API请求
    const response = await api.auth.put(`prompts/${id}`, body);
    
    return NextResponse.json(response);
  } catch (error) {
    console.error('Error updating prompt:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function DELETE(req, { params }) {
  try {
    const { id } = await params; // 修复：先await params，然后解构
    if (!id) {
      return NextResponse.json({ error: '缺少ID' }, { status: 400 });
    }

    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    // 使用带认证的API请求
    await api.auth.delete(`prompts/${id}`);
    
    return NextResponse.json({ message: '删除成功' });
  } catch (error) {
    console.error('Error deleting prompt:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
